package com.gqs.bookstore.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public BaseServlet() {
        super();
    }
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.safeInvoke(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private void safeInvoke(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");//只针对post有效【后台接收前台】
		response.setCharacterEncoding("UTF-8");//【前台接收后台】
		response.setContentType("text/html;charset=utf-8");//servlet中必须添加的   
		//所以由页面传递过来的m方法都会用到上面的设置
		String m = request.getParameter("m");
		if(m != null && !"".equals(m.trim())) {
			try {
				Method method = this.getClass().getDeclaredMethod(m, HttpServletRequest.class,
						HttpServletResponse.class);
				method.invoke(this, request, response);//调用子类方法名是m的方法
			} catch (NoSuchMethodException | SecurityException
					| IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				throw new ServletException("请求参数错误:必须提交名称为m的参数，并且对应的Servlet中的方法名称必须存在", e);
			} 
		}
		else{
			throw new ServletException("请求参数错误:必须提交名称为m的参数，并且对应的Servlet中的方法名称必须存在");
			
		}
	}
}
